package net.zdreamer.shunyi.myview;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.Drawable.ConstantState;
import android.graphics.drawable.DrawableContainer.DrawableContainerState;
import android.graphics.drawable.StateListDrawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.Button;

public class TriangleButton extends Button {

    private Bitmap mBitmap;

    public TriangleButton(Context context) {
        this(context, null);
    }

    public TriangleButton(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TriangleButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            if (mBitmap == null) {
                mBitmap = getBackgroundBitmap();
            }
            if (mBitmap == null) {
                return super.dispatchTouchEvent(event);
            }
            try {
                int pixel = mBitmap.getPixel((int) event.getX(), (int) event.getY());
                if (pixel == 0) {
                    return false;
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
        return super.dispatchTouchEvent(event);
    }

    private Bitmap getBackgroundBitmap() {
        Drawable drawable = getBackground();
        if (drawable == null) {
            return null;
        }

        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        }

        if (drawable instanceof StateListDrawable) {
            StateListDrawable stateListDrawable = (StateListDrawable) drawable;
            ConstantState constantState = stateListDrawable.getConstantState();
            if (constantState instanceof DrawableContainerState) {
                DrawableContainerState drwblContainerState = (DrawableContainerState) constantState;
                Drawable[] drawables = drwblContainerState.getChildren();
                if (drawables == null || drawables.length < 1) {
                    return null;
                }
                for (Drawable drwbl : drawables) {
                    if (drwbl instanceof BitmapDrawable) {
                        return ((BitmapDrawable) drwbl).getBitmap();
                    }
                }
            }
        }

        return null;
    }
}
